#!/bin/sh
# This is a NetworkManager dispatcher script for chronyd to update
# its NTP sources passed from DHCP options. Note that this script is
# specific to NetworkManager-dispatcher due to use of the
# DHCP4_NTP_SERVERS environment variable. For networkd-dispatcher,
# an alternative approach is external means such as a dhclient hook.
#
# Carried in Fedora CoreOS and RHEL CoreOS temporarily.
# See: https://bugzilla.redhat.com/show_bug.cgi?id=1800901

export LC_ALL=C

# Exit if support for dhcp4-change landed in the chrony package.
# See upstream thread: https://listengine.tuxfamily.org/chrony.tuxfamily.org/chrony-dev/2020/05/msg00022.html
[ -f /usr/lib/NetworkManager/dispatcher.d/20-chrony-dhcp ] && \
    grep -q "dhcp4-change" /usr/lib/NetworkManager/dispatcher.d/20-chrony-dhcp && \
    exit 0
[ -f /etc/NetworkManager/dispatcher.d/20-chrony-dhcp ] && \
    grep -q "dhcp4-change" /etc/NetworkManager/dispatcher.d/20-chrony-dhcp && \
    exit 0

interface=$1
action=$2

chrony_helper=/usr/libexec/coreos-chrony-helper
default_server_options=iburst
server_dir=/var/run/coreos-chrony-dhcp

dhcp_server_file=$server_dir/chrony.servers.$interface
# DHCP4_NTP_SERVERS is passed from DHCP options by NetworkManager.
nm_dhcp_servers=$DHCP4_NTP_SERVERS

[ -f /etc/sysconfig/network ] && . /etc/sysconfig/network
[ -f /etc/sysconfig/network-scripts/ifcfg-"${interface}" ] && \
    . /etc/sysconfig/network-scripts/ifcfg-"${interface}"

add_servers_from_dhcp() {
    rm -f "$dhcp_server_file"

    # Don't add NTP servers if PEERNTP=no specified; return early.
    [ "$PEERNTP" = "no" ] && return

    for server in $nm_dhcp_servers; do
        echo "$server ${NTPSERVERARGS:-$default_server_options}" >> "$dhcp_server_file"
    done
    $chrony_helper update-daemon || :
}

clear_servers_from_dhcp() {
    if [ -f "$dhcp_server_file" ]; then
        rm -f "$dhcp_server_file"
        $chrony_helper update-daemon || :
    fi
}

mkdir -p $server_dir

if [ "$action" = "up" ] || [ "$action" = "dhcp4-change" ]; then
    add_servers_from_dhcp
elif [ "$action" = "down" ]; then
    clear_servers_from_dhcp
fi

exit 0
